﻿using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class AudioSourceGetSpectrumDataExample : MonoBehaviour
{
    string msg = "";
    bool first = true;
    void Update()
    {
        float[] spectrum = new float[256];

        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
        //AudioListener.GetOutputData(spectrum, 0);


        for (int i = 1; i < spectrum.Length - 1; i++)
        {
            Debug.DrawLine(new Vector3(i - 1, spectrum[i] + 10, 0), new Vector3(i, spectrum[i + 1] + 10, 0), Color.red);
            Debug.DrawLine(new Vector3(i - 1, Mathf.Log(spectrum[i - 1]) + 10, 2), new Vector3(i, Mathf.Log(spectrum[i]) + 10, 2), Color.cyan);
            Debug.DrawLine(new Vector3(Mathf.Log(i - 1), spectrum[i - 1] - 10, 1), new Vector3(Mathf.Log(i), spectrum[i] - 10, 1), Color.green);
            Debug.DrawLine(new Vector3(Mathf.Log(i - 1), Mathf.Log(spectrum[i - 1]), 3), new Vector3(Mathf.Log(i), Mathf.Log(spectrum[i]), 3), Color.blue);

            Debug.DrawLine(new Vector3(i - 1, spectrum[i - 1], 5), new Vector3(i, spectrum[i], 5), Color.white);
        }

        if (first && Time.time > 2)
        {
            if (GetComponent<AudioSource>().isPlaying)
            {
                first = false;

                Debug.Log(spectrum.Length);
                for (int i = 0; i < spectrum.Length; i++)
                {
                    msg = msg + string.Format("{0:F4},", spectrum[i]);

                    if ( (i+1) % 16 == 0)
                    {
                        msg += "\r\n";
                    }
                }
                Debug.Log(msg);
            }
        }
    }
}